# -*- coding: utf-8 -*-
from scrapy import Request
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

from torrent_crawler import bencode
from torrent_crawler.items import Torrent

from urlparse import parse_qs
from urllib import splitquery
from hashlib import sha1


class BttiantangSpider(CrawlSpider):
    name = "bttiantang"
    allowed_domains = ["www.bttiantang.com"]
    start_urls = (
        'http://www.bttiantang.com/',
    )

    rules = (
        Rule(LinkExtractor(allow=r'.+/subject/\d+\.html'),
             callback='parse_movie_info'),
        Rule(LinkExtractor(allow=r'.+\?PageNo=\d+'))
    )

    def parse_movie_info(self, response):
        torrent_url = response.xpath('//div[@class="tinfo"]/a/@href').extract()
        if len(torrent_url) == 0:
            return

        torrent_url = torrent_url[0]
        params = dict(map(lambda p: (p[0], p[1][0]),
                          parse_qs(splitquery(torrent_url)[1]).iteritems()))

        url = 'http://www.bttiantang.com/download.php'
        body = 'action=download&id=%s&uhash=%s' %\
            (params['id'], params['uhash'])

        return Request(url=url,
                       method='POST', body=body,
                       headers={
                           'Content-Type': 'application/x-www-form-urlencoded'
                       },
                       callback=self.parse_torrent)

    def parse_torrent(self, response):
        meta = bencode.decode(response.body)
        info_hash = sha1(bencode.encode(meta["info"])).hexdigest()
        title = meta['info']['name']
        if 'name.utf-8' in meta['info']:
            title = meta['info']['name.utf-8']

        i = Torrent()
        i['title'] = title
        i['info_hash'] = info_hash
        return i
